<?php
// view_events.php

// 加载环境变量
function load_env($path)
{
    if (!file_exists($path)) {
        return [];
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $env = [];

    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) {
            continue;
        }
        list($name, $value) = array_map('trim', explode('=', $line, 2));
        $env[$name] = trim($value, '"');
    }

    return $env;
}

$env = load_env(__DIR__ . '/.env');

// 数据库连接
$dsn = "mysql:host={$env['DB_HOST']};dbname={$env['DB_NAME']};port={$env['DB_PORT']};charset=utf8mb4";
try {
    $pdo = new PDO($dsn, $env['DB_USER'], $env['DB_PASS'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (PDOException $e) {
    die("数据库连接失败: " . htmlspecialchars($e->getMessage()));
}

// 获取查询参数
$repository = isset($_GET['repository']) ? trim($_GET['repository']) : '';
$owner = isset($_GET['owner']) ? trim($_GET['owner']) : '';
$pusher = isset($_GET['pusher']) ? trim($_GET['pusher']) : '';
$date_from = isset($_GET['date_from']) ? trim($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? trim($_GET['date_to']) : '';

// 构建查询
$query = "SELECT * FROM webhook_events WHERE 1=1";
$params = [];

if ($repository !== '') {
    $query .= " AND repository_name LIKE :repository";
    $params[':repository'] = "%$repository%";
}

if ($owner !== '') {
    $query .= " AND repository_owner LIKE :owner";
    $params[':owner'] = "%$owner%";
}

if ($pusher !== '') {
    $query .= " AND pusher LIKE :pusher";
    $params[':pusher'] = "%$pusher%";
}

if ($date_from !== '') {
    $query .= " AND received_at >= :date_from";
    $params[':date_from'] = $date_from . " 00:00:00";
}

if ($date_to !== '') {
    $query .= " AND received_at <= :date_to";
    $params[':date_to'] = $date_to . " 23:59:59";
}

$query .= " ORDER BY received_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$events = $stmt->fetchAll();

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>DCO Webhook 事件查询</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        table { border-collapse: collapse; width: 100%; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; }
        th { background-color: #f2f2f2; }
        .filter-form { margin-bottom: 20px; }
        .invalid-commits { margin-top: 10px; }
    </style>
</head>
<body>
    <h1>DCO Webhook 事件查询</h1>
    <form method="get" class="filter-form">
        <label>
            仓库名称:
            <input type="text" name="repository" value="<?php echo htmlspecialchars($repository); ?>">
        </label>
        <label>
            仓库所有者:
            <input type="text" name="owner" value="<?php echo htmlspecialchars($owner); ?>">
        </label>
        <label>
            推送者:
            <input type="text" name="pusher" value="<?php echo htmlspecialchars($pusher); ?>">
        </label>
        <label>
            日期从:
            <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
        </label>
        <label>
            日期到:
            <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
        </label>
        <button type="submit">查询</button>
        <button type="button" onclick="window.location.href='view_events.php'">重置</button>
    </form>

    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>仓库名称</th>
                <th>仓库所有者</th>
                <th>推送者</th>
                <th>Ref</th>
                <th>Before SHA</th>
                <th>After SHA</th>
                <th>接收时间</th>
                <th>无效提交</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($events)): ?>
                <tr><td colspan="9">没有找到匹配的事件。</td></tr>
            <?php else: ?>
                <?php foreach ($events as $event): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($event['id']); ?></td>
                        <td><?php echo htmlspecialchars($event['repository_name']); ?></td>
                        <td><?php echo htmlspecialchars($event['repository_owner']); ?></td>
                        <td><?php echo htmlspecialchars($event['pusher']); ?></td>
                        <td><?php echo htmlspecialchars($event['ref']); ?></td>
                        <td><?php echo htmlspecialchars($event['before_sha']); ?></td>
                        <td><?php echo htmlspecialchars($event['after_sha']); ?></td>
                        <td><?php echo htmlspecialchars($event['received_at']); ?></td>
                        <td>
                            <?php
                                // 查询该事件对应的无效提交
                                $stmt_invalid = $pdo->prepare("SELECT * FROM invalid_commits WHERE sha IN (SELECT sha FROM commits_in_event WHERE event_id = :event_id)");
                                // 假设有一个关联表 commits_in_event
                                // 如果没有，可以根据实际情况调整
                                // 这里假设 invalid_commits 已经关联到 webhook_events
                                // 例如，可以在 invalid_commits 表中添加 event_id 字段
                                // 这里简化处理，直接查询所有 invalid_commits 的数量
                                $stmt_invalid = $pdo->prepare("SELECT * FROM invalid_commits WHERE detected_at >= :start_time AND detected_at <= :end_time");
                                $stmt_invalid->execute([
                                    ':start_time' => $event['received_at'] . " 00:00:00",
                                    ':end_time' => $event['received_at'] . " 23:59:59",
                                ]);
                                $invalids = $stmt_invalid->fetchAll();
                                if (empty($invalids)) {
                                    echo "无";
                                } else {
                                    echo "<a href='#' onclick='toggleInvalidCommits({$event['id']}); return false;'>查看 (" . count($invalids) . ")</a>";
                                    echo "<div id='invalid-commits-{$event['id']}' class='invalid-commits' style='display:none;'>";
                                    foreach ($invalids as $invalid) {
                                        echo "<strong>SHA:</strong> " . htmlspecialchars($invalid['sha']) . "<br>";
                                        echo "<strong>作者:</strong> " . htmlspecialchars($invalid['author']) . "<br>";
                                        echo "<strong>消息:</strong> " . nl2br(htmlspecialchars($invalid['message'])) . "<br>";
                                        echo "<strong>链接:</strong> <a href='" . htmlspecialchars($invalid['url']) . "' target='_blank'>查看提交</a><br><br>";
                                    }
                                    echo "</div>";
                                }
                            ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

    <script>
        function toggleInvalidCommits(eventId) {
            var div = document.getElementById('invalid-commits-' + eventId);
            if (div.style.display === 'none') {
                div.style.display = 'block';
            } else {
                div.style.display = 'none';
            }
        }
    </script>
</body>
</html>
